package com.ruoyi.system.conf;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.dynamic.domain.UserDynamic;
import com.ruoyi.dynamic.domain.UserParty;
import com.ruoyi.dynamic.mapper.UserDynamicMapper;
import com.ruoyi.dynamic.mapper.UserPartyMapper;

/**
 *	redis 过期key 监听
 * @author DEREK
 */
@Component
public class RedisKeyExpiredListener extends KeyExpirationEventMessageListener{

	@Autowired
	private UserDynamicMapper userDynamcMapper;
	@Autowired
	private UserPartyMapper userPartyMapper;
	@Autowired
	private RedisUtil redisUtil;
	
	public RedisKeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}
	
	@Override
	public void onMessage(Message message, byte[] pattern) {
		System.out.println("redis回调过期key:"+message);
		if(null == message) {
			return;
		}
		String result = message.toString();
		if(!result.contains("-")) {
			return;
		}
		if(!result.contains("sweet")) {
			return;
		}
		String[] split = result.split("-");
		if(split.length != 3) {
			return;
		}
		// 类型
		String type = split[0];
		Long relatedId = Long.valueOf(split[1]);
		if("dynamic".equals(type)) {
			UserDynamic dynamic = new UserDynamic();
			dynamic.setId(relatedId);
			dynamic.setCreateTime(new Date());
			userDynamcMapper.updateById(dynamic);
		}else {
			UserParty party = new UserParty();
			party.setId(relatedId);
			party.setCreateTime(new Date());
			userPartyMapper.updateById(party);
		}
		
//		String[] split = result.split("-");
//		if(split.length != 3) {
//			return;
//		}
//		// 相关id
//		Long relatedId = Long.valueOf(split[0]);
//		// 1=动态 2=约玩
//		Integer type = Integer.valueOf(split[1]);
//		// 1=24h 2=48h
//		Integer time = Integer.valueOf(split[2]);
//		Date nowDate = new Date();
//		if(1 == type) {
//			UserDynamic dynamic = new UserDynamic();
//			dynamic.setId(relatedId);
//			dynamic.setCreateTime(nowDate);
//			userDynamcMapper.updateById(dynamic);
//		}else {
//			UserParty party = new UserParty();
//			party.setId(relatedId);
//			party.setCreateTime(nowDate);
//			userPartyMapper.updateById(party);
//		}
//		Date pastDateTime = DateUtils.getPastDateTime(time, nowDate, 2);
//		long expireTime = DateUtils.getDaySecond(nowDate, pastDateTime);
//		String key = relatedId+"-"+type+"-"+time;
//		redisUtil.set(key, key, expireTime);
	}
}
